//
//  PublicityViewModel.m
//  EnvironmentalProtection
//
//  Created by HCreater on 2018/11/26.
//  Copyright © 2018年 HCreater. All rights reserved.
//

#import "PublicityV2ViewModel.h"

#import "ArticleInfoData.h"
#import "ArticlesListData.h"
#import "PublicityListCell.h"

@interface PublicityV2ViewModel()

@property (nonatomic, readwrite, strong) NSArray* types;
@property (nonatomic, strong) CateInfoData* chooseType;

@property (nonatomic, readwrite, strong) RACCommand* requestDataCmd;
@property (nonatomic, readwrite, strong) RACCommand* moreCmd;
@property (nonatomic, readwrite, strong) RACCommand* requestDetailCmd;
@property (nonatomic, readwrite, strong) RACCommand* delCmd;

@property (nonatomic, readwrite, strong) RACCommand* selectCmd;

@property (nonatomic, strong) NSArray* moreOptions;

@end

@implementation PublicityV2ViewModel

- (void)initialize
{
    [super initialize];
    
    @weakify(self);
    
    DataManager* dm = [DataManager sharedDataManager];
    
    NSMutableArray* tmpTypes = [NSMutableArray array];
    for (NSInteger index=0; index<dm.publicityCateInfos.datas.count; index++)
    {
        CateInfoData* curCateInfo = dm.publicityCateInfos.datas[index];
        
        [tmpTypes addObject:curCateInfo.cateName];
    }
    self.types = tmpTypes;
    self.chooseType = nil;
    self.chooseIndex = -1;
    
    RAC(self, chooseType) = [[RACObserve(self, chooseIndex) distinctUntilChanged] map:^id(id value)
    {
        NSInteger valueInt = [value integerValue];
        
        if (valueInt == -1)
            return nil;
        
        CateInfoData* curCateInfo = dm.publicityCateInfos.datas[valueInt];
        
        return curCateInfo;
    }];
    
    RAC(self, typeName) = [[RACObserve(self, chooseType) distinctUntilChanged] map:^id(id value)
    {
        @strongify(self);
        
        if (!value)
            return @"全部";
        
        CateInfoData* curCateInfo = value;
        
        [self.requestRemoteDataCommand execute:@0];
        
        return curCateInfo.cateName;
    }];
    
    self.moreOptions = @[@"删除", @"取消"];
    
    self.cellHeight = 100.0f;
    
    /// viewDidLoad后加载数据
    self.shouldRequestRemoteDataOnViewDidLoad = NO;
    /// 允许下拉刷新
    self.shouldPullDownToRefresh = YES;
    /// 允许上拉加载
    self.shouldPullUpToLoadMore = YES;
    
    /// 请求数据
    //    self.requestDataCmd = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id inputInfo) {
    //
    //        @strongify(self);
    //
    //        NSInteger loadIndex = [inputInfo[@"LoadIndex"] integerValue];
    //
    //        return [self requestListDataSignalWithPageIndex:loadIndex pageSize:2];
    //    }];
    
    /// 选中
    self.selectCmd = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(NSIndexPath* indexPath)
                      {
                          @strongify(self);
                          
                          PublicityListCellModel* itemViewModel = self.dataSource[indexPath.row];
                          
                          ArticleListData* alistData = itemViewModel.data;
                          
                          return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
                              dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0), dispatch_get_main_queue(), ^{
                                  [subscriber sendNext:alistData];
                                  [subscriber sendCompleted];
                              });
                              return nil;
                          }];
                      }];
    // 允许并行执行
    self.selectCmd.allowsConcurrentExecution = NO;
    
    self.moreCmd = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(PublicityListCell* ivm)
                    {
                        @strongify(self);
                        
                        NSInteger findIndex = -1;
                        
                        for (NSInteger index=0; index<self.dataSource.count; index++)
                        {
                            PublicityListCell* itemViewModel = self.dataSource[index];
                            
                            if (ivm == itemViewModel)
                            {
                                findIndex = index;
                                
                                break;
                            }
                        }
                        
                        return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
                            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0), dispatch_get_main_queue(), ^{
                                [subscriber sendNext:@(findIndex)];
                                [subscriber sendCompleted];
                            });
                            return nil;
                        }];
                    }];
    
    self.delCmd = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input)
                   {
                       @strongify(self);
                       
                       @weakify(self);
                       return [[self _requestDelSignal:input] doNext:^(id x)
                               {
                                   @strongify(self);
                                   
                                   [self _delDataByIndex:[input integerValue]];
                               }];
                   }];
    
    self.requestDetailCmd = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input)
                             {
                                 return [self _requestDetailSignal:input];
                             }];
}

- (void)_delDataByIndex:(NSInteger)dataIndex
{
    NSMutableArray* copyDataSource = [NSMutableArray arrayWithArray:[self.dataSource copy]];
    [copyDataSource removeObjectAtIndex:dataIndex];
    
    self.dataSource = copyDataSource;
}

- (RACSignal*)_requestDelSignal:(NSNumber*)delNum
{
    @weakify(self);
    
    PublicityListCellModel* delIVM = self.dataSource[[delNum integerValue]];
    
    ArticleListData* curAListData = delIVM.data;
    
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber)
            {
                @strongify(self);
                
                @weakify(self);
                [[AFNetWorkUtils racPOSTWthURL:url_interface_stwxdel params:interface_param_stwxdel(curAListData.articleID)] subscribeNext:^(id x)
                 {
                     [subscriber sendNext:x[SUCommandSysMessageKey]];
                     [subscriber sendCompleted];
                 } error:^(NSError *error)
                 {
                     NSString* strError = [error.userInfo[customErrorInfoKey] isNotBlank] ? error.userInfo[customErrorInfoKey] : @"请求删除失败";
                     [subscriber sendError:[NSError errorWithDomain:SUCommandErrorDomain code:SUCommandErrorCode userInfo:@{SUCommandErrorUserInfoKey:strError}]];
                     [subscriber sendCompleted];
                 }];
                
                return nil;
            }];
}

- (RACSignal *)_requestDetailSignal:(NSString*)articleID
{
    @weakify(self);
    
    UserManagerV2* um = [UserManagerV2 sharedUserManagerV2];
    NSString* userID = HCStrValid(um.userData.userID);

    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber)
            {
                @strongify(self);
                
                @weakify(self);
                [[AFNetWorkUtils racPOSTWthURL:url_interface_articledetail params:interface_param_articledetail(articleID, userID)] subscribeNext:^(id x)
                 {
                     ArticleInfoData* data = [ArticleInfoData modelWithJSON:x];
                     
                     StwxDetailItemViewModel* ivm = [[StwxDetailItemViewModel alloc] initWithData:data cellHeight:self.cellHeight];
                     
                     [subscriber sendNext:ivm];
                     [subscriber sendCompleted];
                 } error:^(NSError *error)
                 {
                     NSString* strError = [error.userInfo[customErrorInfoKey] isNotBlank] ? error.userInfo[customErrorInfoKey] : @"请求详情失败";
                     [subscriber sendError:[NSError errorWithDomain:SUCommandErrorDomain code:SUCommandErrorCode userInfo:@{SUCommandErrorUserInfoKey:strError}]];
                     [subscriber sendCompleted];
                 }];
                
                return nil;
            }];
}

- (RACSignal *)requestRemoteDataSignalWithPage:(NSUInteger)page
{
    @weakify(self)
    
    UserManagerV2* um = [UserManagerV2 sharedUserManagerV2];
    
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        
        @strongify(self);
        
        NSString* cateID = self.chooseType==nil ? @"" : self.chooseType.cateID;
        
        @weakify(self);
        [[AFNetWorkUtils racPOSTWthURL:url_interface_usernotice params:interface_param_usernotice(um.userData.userID, cateID, @(page+1), @(List_PageSize))] subscribeNext:^(id x)
         {
             @strongify(self);
             
             NSDictionary* result = @{};
             
             NSDictionary* callbackDic = x;
             if ([callbackDic.allKeys containsObject:@"datas"])
             {
                 result = @{@"articleList":x[@"datas"]};
             }
             else
             {
                 result = @{@"articleList":@[]};
             }
             
             ArticlesListData* data = [ArticlesListData modelWithJSON:result];
             
             @weakify(self);
             NSArray *viewModels = [data.datas.rac_sequence map:^PublicityListCellModel *(ArticleListData* aListData)
                                    {
                                        @strongify(self);
                                        
                                        @weakify(self);
                                        PublicityListCellModel *itemViewModel = [[PublicityListCellModel alloc] initWithData:aListData cellHeight:self.cellHeight];
                                        [itemViewModel.moreCmd.executionSignals.switchToLatest subscribeNext:^(id x)
                                         {
                                             @strongify(self);
                                             
                                             [self.moreCmd execute:itemViewModel];
                                         }];
                                        
                                        return itemViewModel;
                                    }].array;
             
             if (self.shouldPullUpToLoadMore)
             {
                 if (0 == page)
                 {
                     self.dataSource = viewModels;
                 }
                 else
                 {
                     if (self.dataSource == nil)
                     {
                         self.dataSource = viewModels;
                     }
                     else
                     {
                         self.dataSource = [self.dataSource arrayByAddingObjectsFromArray:viewModels];
                     }
                 }
             }
             else
             {
                 self.dataSource = viewModels;
             }
             
             [subscriber sendNext:nil];
             [subscriber sendCompleted];
         }];
        
        return nil;
    }];
}

@end
